package Hxw3DEngine.core.component.renderer
{
	import flash.utils.ByteArray;
	import Hxw3DEngine.core.component.Skeleton;
	import Hxw3DEngine.core.display.GameObject;
	import Hxw3DEngine.core.component.animation.SkeletonAnimation;
	import Hxw3DEngine.core.Resource.geometry.ResourceGeometry;
	import flash.utils.Endian;
	import ao3s2.Flash3dLib.CModule;
	import Hxw3DEngine.core.materials.shader.SkinnedShader;
	
	/**
	 * ...
	 * @author lighter
	 */
	public class SkinnedMeshRenderer extends MeshRenderer
	{
		private var _skeleton:Skeleton;
		// 骨骼定点数据是否发生了改变
		private var jointsPoseChanged:Boolean = true;
		
		// 将要设置给寄存器的常数
		static private var _vcData:ByteArray = null;
		// cc 骨骼动画最后的计算结果
		static private var _condensedJointSkinMatrices:int = 0;
		
		//static initializer
		{
			_vcData = new ByteArray();
			_vcData.endian = Endian.LITTLE_ENDIAN;
			_vcData.length = 32 * 56;
			(function():void {
				for (var i:int = 0; i < 56; i++)
				{
					for (var j:int = 0; j < 2; j++)
					{
						_vcData.writeFloat(0.0);
						_vcData.writeFloat(0.0);
						_vcData.writeFloat(0.0);
						_vcData.writeFloat(1.0);
					}
				}
			}());			
			_condensedJointSkinMatrices = CModule.malloc(32 * 56);
		}
		
		
		
		public function SkinnedMeshRenderer()
		{
			super();
		}
		
		override public function onAdd(master:GameObject):void
		{
			super.onAdd(master);
			_skeleton = _object3d.getComponent(Skeleton) as Skeleton;
		}
		
		override public function onDraw():void
		{
			var anim:SkeletonAnimation = _object3d.getComponent(SkeletonAnimation) as SkeletonAnimation;
			
			if (anim != null) {
			   // cc 指针在 ResourceGeometry中。从动画设置紧缩动画矩阵。
			   Flash3dLib.getCondensedSkinDatas(
				   _condensedJointSkinMatrices,
				   anim.jointPoseDatas,
				   _geometry.joints,
				   _geometry.numberOfJoints,
				   anim.dualQuat?1:0);
			   // 从cc内存拷贝到
			   var length:int = _geometry.numberOfJoints * (anim.dualQuat?32:48);
			   _vcData.position = 0;
			   CModule.readBytes(_condensedJointSkinMatrices, length, _vcData);
			   _vcData.position = 0;
			
			   // 设置给Shader的寄存器
			   SkinnedShader(material.shader).setBoneData(_vcData, length);
			
			   jointsPoseChanged = true;
			}
			super.onDraw();
		}
	}
}